package com.usian.day02.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.usian.common.model.day01.User;
import com.usian.common.model.day02.Order;
import com.usian.common.vo.ResultResopnse;
import com.usian.day02.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2023/7/27 8:51
 */
@RestController
@RequestMapping("/order")
@RefreshScope
@Slf4j
public class OrderController {

    /**
     * @Value 和配置文件做映射
     */
    @Value("${test.name}")
    public String name;

    @GetMapping("/test1")
    public ResultResopnse test1(){
        log.info("The 8611 is :{}",name);
        return ResultResopnse.success(name);
    }

    @Autowired
    OrderService orderService;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/test")
    public String test(){
        return "OK";
    }


    @GetMapping("list")
    public ResultResopnse list(HttpServletRequest request,HttpSession session){
        try{


            String token = request.getHeader("token");
            log.info("token :{}",token);

            Object sessionAttribute = session.getAttribute(token);
            log.info("sessionAttribute :{}",sessionAttribute);

            String  o = (String)redisTemplate.opsForValue().get(token);

            log.info("o :{}",o);

            User user = JSONObject.parseObject(o, User.class);

            List<Order> list = orderService.list();

            return ResultResopnse.success(list);
        }catch(Exception e){
            e.printStackTrace();
            return ResultResopnse.error();
        }

    }

    @PostMapping("save")
    public ResultResopnse save(@RequestBody Order order){
        try{
            boolean b = orderService.save(order);
            return ResultResopnse.success(b);
        }catch(Exception e){
            e.printStackTrace();
            return ResultResopnse.error();

        }

    }

    @GetMapping("/{id}")
    public ResultResopnse findById(@PathVariable String id){
        try{
            Order order = orderService.getById(id);
            return ResultResopnse.success(order);

        }catch (Exception e){
            e.printStackTrace();
            return ResultResopnse.error();
        }

    }


}
